package order.demo.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

/**
 * 登陆页面
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 一.获取用户信息
		request.setCharacterEncoding("utf-8");
		String username = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		// 二.验证登陆
		if ("jon".equalsIgnoreCase(username)) {
			// 1.保存用户信息到session
			/*
			 * getSession()：
			 * 				1.如果浏览器中cookie有JSESSIONID，则获取JSESSIONID
			 * 				2.没有则创建session
			 * getSession(false)：如果浏览器中cookie的JSESSIONID不存在，则不创建session
			 */
			request.getSession().setAttribute("username", username);
			// 2.将用户名保存到cookie中，让浏览器记住用户名
			Cookie cookie = new Cookie("uname", username);
			cookie.setMaxAge(60*60*24);
			response.addCookie(cookie);
			// 3.重定向到成功页面
			response.sendRedirect("/OrderSystem/index.jsp");
		} else {
			// 1.保存错误信息到cookie
			request.setAttribute("msg", "用户名或密码错误");
			// 2.转发到登陆页面（转发直接从WebContent路径下）
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

}
